package com.choosefine.springboot.devops.user.controller;


import com.choosefine.springboot.devops.base.config.MapUtil;
import com.choosefine.springboot.devops.base.result.ReturnMSG;
import com.choosefine.springboot.devops.user.dto.InsertUserDTO;
import com.choosefine.springboot.devops.user.dto.UpdateUserDTO;
import com.choosefine.springboot.devops.user.model.User;
import com.choosefine.springboot.devops.user.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private ObjectMapper objectMapper;

	@GetMapping("/{id}")
	public String selectById(@PathVariable("id") Integer id) throws JsonProcessingException {
		User result=userService.selectById(id);
		return objectMapper.writeValueAsString(result);
	}

	@GetMapping("/code/{wxCode}")
	public String selectByCode(@PathVariable("wxCode") String wxCode) throws JsonProcessingException {
		User result=userService.selectByCode(wxCode);
		return objectMapper.writeValueAsString(result);
	}

	@PostMapping
	public String insert(@Valid InsertUserDTO insertUserDTO, BindingResult result) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		if(result.hasErrors()){
			return objectMapper.writeValueAsString(returnMSG.paramError());
		}else{
			userService.save(User.class, MapUtil.transBean2Map(insertUserDTO));
			return objectMapper.writeValueAsString(returnMSG.success());
		}
	}

	@PutMapping
	public String update(@Valid UpdateUserDTO updateUserDTO, BindingResult result) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		if(result.hasErrors()){
			return objectMapper.writeValueAsString(returnMSG.paramError());
		}else{
			if(userService.update(User.class, MapUtil.transBean2Map(updateUserDTO))>0){
				return objectMapper.writeValueAsString(returnMSG.success());
			}else{
				return objectMapper.writeValueAsString(returnMSG.error());
			}
		}
	}

	@DeleteMapping
	public String delete(Integer id) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		if(id==null){
			return objectMapper.writeValueAsString(returnMSG.paramError());
		}else{
			Map param=new HashMap();
			param.put("id",id);
			if(userService.falseDelete(User.class,param)>0){
				return objectMapper.writeValueAsString(returnMSG.success());
			}else{
				return objectMapper.writeValueAsString(returnMSG.error());
			}
		}
	}

}
